package com.huajx.core.handler;

import com.huajx.core.message.RequestMessage;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;

/**
 * TCP 处理适配器
 */
public abstract class ServerHandlerFactory extends IoHandlerAdapter {
    /**
     * 处理器
     */

    public abstract HandlerAdapter getHandler(Object message);

    protected RequestMessage getRequestMessage(){
        return new RequestMessage();
    }

//    public void setHandler(HandlerAdapter handler) {
//        this.handler = handler;
//    }

    @Override
    public void sessionOpened(IoSession session) {
        // set idle time to 60 seconds
        session.getConfig().setIdleTime(IdleStatus.BOTH_IDLE, 60);
    }

    @Override
    public void messageReceived(IoSession session, Object message) {
        RequestMessage request = getRequestMessage();
        request.setSession(session);
        request.setMessage(message);
        HandlerAdapter handler = getHandler(message);
        if(handler != null) {
            handler.handler(request);
            handler.render(session);
        }
    }

    @Override
    public void sessionIdle(IoSession session, IdleStatus status) {
        session.closeOnFlush();
    }

    @Override
    public void exceptionCaught(IoSession session, Throwable cause) {
        session.closeOnFlush();
    }
}
